<template>
    <div>
        <el-container>
            <el-header class="topBox">
                <!-- 顶部导航栏保持不变 -->
                <!-- logo和标题 -->
                <div style="display: flex;" class="ai-c">
                    <div class="logoImg">
                        <div>Easys互动管理平台</div>
                    </div>
                    <div style="margin-left: 30px; margin-top: 0; font-size: 22px; font-weight: bold; color: #ffffff">

                    </div>
                </div>
                <div class="topBoxitem abs-y">
                    <div style="display: flex; align-items: center">
                        <img src="../assets/iconImg/msg.png" style="width: 15px; height: 15px" />
                        <div style="margin-left: 6px; color: #fff; cursor: pointer;">消息</div>
                    </div>
                    <div style="color: #eeeeee">|</div>
                    <div @click="clickLogout" style="display: flex; align-items: center">
                        <img src="../assets/iconImg/user_a.png" style="width: 25px; height: 25px" />
                        <div style="color: #fff; font-size: 15px; margin-left: 6px; cursor: pointer;">
                            {{ userName ? userName : 'logout' }}
                        </div>
                    </div>
                </div>
            </el-header>
            <el-container>
                <el-aside class="leftBox">
                    <div class="leftBoxConent">
                        <!-- 使用 el-menu 重构左侧导航 -->
                        <el-menu :default-active="activeMenu" :default-openeds="openedMenus"
                            class="el-menu-vertical-demo" @select="handleMenuSelect" router :unique-opened="false">
                            <!-- 1. 站点列表 -->
                            <el-sub-menu index="1">
                                <template #title>
                                    <div class="leftTitle">
                                        <div class="fcc">
                                            <img src="../assets/iconImg/zd.png" class="fccIcon" />
                                            <div class="iconMl">站点列表</div>
                                        </div>
                                    </div>
                                </template>
                                <template v-for="(site, siteIndex) in siteAdminList" :key="siteIndex">
                                    <el-sub-menu :index="`1-${siteIndex}`">
                                        <template #title>
                                            <div style="margin-left: 10px; font-size: 14px;">
                                                {{ site.activity_name }}
                                            </div>
                                        </template>
                                        <el-menu-item :index="`/siteRetention?site=${site.id}`"
                                            @click="changeColor(1, siteIndex, 'retention')">
                                            <div
                                                :style="{ color: isActive(1, siteIndex, 'retention') ? '#3a7bb8' : '#9a9a9a' }">
                                                站点留资
                                            </div>
                                        </el-menu-item>
                                        <el-menu-item :index="`/siteOperation?site=${site.id}`"
                                            @click="changeColor(1, siteIndex, 'operation')">
                                            <div
                                                :style="{ color: isActive(1, siteIndex, 'operation') ? '#3a7bb8' : '#9a9a9a' }">
                                                运营数据
                                            </div>
                                        </el-menu-item>
                                        <el-menu-item :index="`/siteVerification?site=${site.id}`"
                                            @click="changeColor(1, siteIndex, 'verification')">
                                            <div
                                                :style="{ color: isActive(1, siteIndex, 'verification') ? '#3a7bb8' : '#9a9a9a' }">
                                                抽奖核销
                                            </div>
                                        </el-menu-item>
                                    </el-sub-menu>
                                </template>
                            </el-sub-menu>

                            <!-- 2. 站点运营 -->
                             <template v-if="user.level == 1">
                             <el-sub-menu index="2">
                                <template #title>
                                    <div class="leftTitle">
                                        <div class="fcc">
                                            <img src="../assets/iconImg/giftAdmin.png" class="fccIcon" />
                                            <div class="iconMl">站点运营</div>
                                        </div>
                                    </div>
                                </template>
                                <template v-for="(site, siteIndex) in siteAdminList" :key="siteIndex">
                                    <el-sub-menu :index="`1-${siteIndex}`">
                                        <template #title>
                                            <div style="margin-left: 10px; font-size: 14px;">
                                                {{ site.activity_name }}
                                            </div>
                                        </template>
                                        <el-menu-item :index="`/siteGiftConfig?site=${site.id}`"
                                            @click="changeColor(1, siteIndex, 'retention')">
                                            <div
                                                :style="{ color: isActive(1, siteIndex, 'retention') ? '#3a7bb8' : '#9a9a9a' }">
                                                站点礼品详情
                                            </div>
                                        </el-menu-item>
                                        <el-menu-item :index="`/siteStockConfig?site=${site.id}`"
                                            @click="changeColor(1, siteIndex, 'operation')">
                                            <div
                                                :style="{ color: isActive(1, siteIndex, 'operation') ? '#3a7bb8' : '#9a9a9a' }">
                                                站点库存详情
                                            </div>
                                        </el-menu-item>
                                    </el-sub-menu>
                                </template>
                            </el-sub-menu>
                            </template>


                            <template v-if="user.level == 1">
                                <!-- 2. 创建站点 -->
                                <el-menu-item index="/createSite" @click="changeColor(2)">
                                    <div class="leftTitle" :style="{ color: changeId === 2 ? '#3a7bb8' : '' }">
                                        <div class="fcc">
                                            <img src="../assets/iconImg/add.png" class="fccIcon" />
                                            <div class="iconMl">创建站点</div>
                                        </div>
                                    </div>
                                </el-menu-item>

                                <!-- 3. 站点管理 -->
                                <el-sub-menu index="3">
                                    <template #title>
                                        <div class="leftTitle">
                                            <div class="fcc">
                                                <img src="../assets/iconImg/setting.png" class="fccIcon" />
                                                <div class="iconMl">站点管理</div>
                                            </div>
                                        </div>
                                    </template>
                                    <template v-for="(site, siteIndex) in siteAdminList" :key="`manage-${siteIndex}`">
                                        <el-sub-menu :index="`3-${siteIndex}`">
                                            <template #title>
                                                <div style="margin-left: 10px; font-size: 14px;">
                                                    {{ site.activity_name }}
                                                </div>
                                            </template>
                                            <el-menu-item :index="`/siteConfig?site=${site.id}`"
                                                @click="changeColor(3, siteIndex, 'config')">
                                                <div
                                                    :style="{ color: isActive(3, siteIndex, 'config') ? '#3a7bb8' : '#9a9a9a' }">
                                                    基础信息配置
                                                </div>
                                            </el-menu-item>
                                            <el-menu-item :index="`/siteProjects?site=${site.id}`"
                                                @click="changeColor(3, siteIndex, 'projects')">
                                                <div
                                                    :style="{ color: isActive(3, siteIndex, 'projects') ? '#3a7bb8' : '#9a9a9a' }">
                                                    活动项目管理
                                                </div>
                                            </el-menu-item>
                                        </el-sub-menu>
                                    </template>
                                </el-sub-menu>

                                <!-- 4. 账号管理 -->
                                <el-menu-item index="/siteAdmin" @click="changeColor(7)">
                                    <div class="leftTitle" :style="{ color: changeId === 7 ? '#3a7bb8' : '' }">
                                        <div class="fcc">
                                            <img src="../assets/iconImg/ren.png" class="fccIcon" />
                                            <div class="iconMl">账号管理</div>
                                        </div>
                                    </div>
                                </el-menu-item>


                            </template>
                        </el-menu>
                    </div>
                </el-aside>
                <el-main class="conentBox">
                    <router-view :key="route.fullPath" />
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script>
import { useRoute, useRouter } from "vue-router";
import { ref, reactive, onMounted, onUnmounted, toRefs, watch } from "vue";
import http from "../libs/http";
import { ElMessageBox, ElMessage } from "element-plus";

export default {
    setup() {
        const route = useRoute();
        const router = useRouter();

        const state = reactive({
            siteAdminList: [],
            changeId: 0,
            activeSiteIndex: null,
            activeSubItem: null,
            activeMenu: route.path, // 当前激活菜单
            openedMenus: ['1', '1-0'], // 默认展开的菜单
            userName: "",
            user: "",
        });

        // 初始化菜单状态
        const initMenuState = () => {
            // 根据当前路由设置激活状态
            const pathMap = {
                '/siteRetention': { id: 1, type: 'retention' },
                '/siteOperation': { id: 1, type: 'operation' },
                '/siteVerification': { id: 1, type: 'verification' },
                '/createSite': { id: 2 },
                '/siteConfig': { id: 3, type: 'config' },
                '/siteProjects': { id: 3, type: 'projects' },
                '/siteAdmin': { id: 7 }
            };

            const routeInfo = pathMap[route.path];
            if (routeInfo) {
                state.changeId = routeInfo.id;
                if (routeInfo.type) {
                    // 尝试从路由参数中获取站点索引
                    const siteId = route.query.site;
                    if (siteId) {
                        const siteIndex = state.siteAdminList.findIndex(site => site.id == siteId);
                        if (siteIndex !== -1) {
                            state.activeSiteIndex = siteIndex;
                            state.activeSubItem = routeInfo.type;


                        }
                    }
                }
            }
        };
        const fetchSiteList = async () => {
            const param = {
                token: localStorage.getItem("openid"),
            };
            const res = await http.$post("/hd_project/Backend/getActivityList", param);
            if (res.code === 200) {
                state.siteAdminList = res.data;
                localStorage.setItem('siteAdminList', JSON.stringify(res.data));
                initMenuState();
                // 新增：默认导航到第一个站点的站点留资页面
                if (state.siteAdminList.length > 0 && route.path === '/') {
                    const firstSiteId = state.siteAdminList[0].id;
                    router.replace({
                        path: '/siteRetention',
                        query: { site: firstSiteId }
                    });
                }
            } else {
                localStorage.clear();
                router.push("/login");
            }
        };

        onMounted(async () => {

            // fetchSiteList();
            // 获取缓存中的user 渲染在页面上
            state.user = JSON.parse(localStorage.getItem("user"));
            console.log(state.user)
            if (localStorage.getItem("userName")) {
                state.userName = localStorage.getItem("userName");
            }

            // 添加事件监听器
            window.addEventListener('updateSiteList', fetchSiteList);
            await fetchSiteList(); // 确保获取站点列表

            // // 获取站点列表
            // const param = {
            //     token: localStorage.getItem("openid"),
            // };
            // const res = await http.$post("/hd_project/Backend/getActivityList", param);
            // if (res.code === 200) {
            //     state.siteAdminList = res.data;

            //     // 把数据存储到本地存储中
            //     localStorage.setItem('siteAdminList', JSON.stringify(res.data));

            //     initMenuState();

            //     // 如果当前在站点相关页面但没有激活的站点，默认选中第一个站点
            //     if ([1, 3].includes(state.changeId) && state.activeSiteIndex === null && state.siteAdminList.length > 0) {
            //         state.activeSiteIndex = 0;
            //         state.activeSubItem = state.changeId === 1 ? 'retention' : 'config';

            //         // 自动跳转到默认页面
            //         const defaultRoutes = {
            //             1: '/siteRetention',
            //             3: '/siteConfig'
            //         };
            //         router.push({
            //             path: defaultRoutes[state.changeId],
            //             query: { site: state.siteAdminList[0].id }
            //         });
            //     }
            // } else {
            //     localStorage.clear();
            //     router.push("/login");
            // }
        });
        // 组件卸载时移除事件监听
        onUnmounted(() => {
            window.removeEventListener('updateSiteList', fetchSiteList);
        });
        // 监听路由变化
        watch(() => route.path, (newPath) => {
            state.activeMenu = newPath;
            initMenuState();
        });

        // 改变选中状态
        const changeColor = (id, siteIndex = null, subItem = null) => {
            state.changeId = id;
            state.activeSiteIndex = siteIndex;
            state.activeSubItem = subItem;

            // 如果点击有子菜单的一级菜单，展开并选中第一个子项
            if ([1, 3].includes(id) && siteIndex === null) {
                state.activeSiteIndex = 0;
                state.activeSubItem = id === 1 ? 'retention' : 'config';

                // 自动跳转到第一个子项
                const firstChildRoutes = {
                    1: '/siteRetention',
                    3: '/siteConfig'
                };
                if (state.siteAdminList.length > 0) {
                    router.push({
                        path: firstChildRoutes[id],
                        query: { site: state.siteAdminList[0].id }
                    });
                }
            }
        };

        // 检查是否激活状态
        const isActive = (id, siteIndex, subItem) => {
            return (
                state.changeId === id &&
                state.activeSiteIndex === siteIndex &&
                state.activeSubItem === subItem
            );
        };

        // 退出登录（保持不变）
        const clickLogout = () => {
            ElMessageBox.confirm("是否要退出登录?", {
                confirmButtonText: "退出",
                cancelButtonText: "取消",
                confirmButtonClass: "confirmBtn",
            })
                .then(async () => {
                    localStorage.clear();
                    router.push("/login");
                    // let param = {
                    //     openid: localStorage.getItem("openid"),
                    // };
                    // const res = await http.$get("/apies/Logout", param);
                    // if (res.code == 200) {
                    //     console.log(">>>>>>退出成功了", res);
                    //     localStorage.clear();
                    //     router.push("/login");
                    // } else {
                    //     ElMessage({
                    //         message: "退出登录失败！",
                    //         type: "warning",
                    //     });
                    // }
                })
                .catch(() => {
                    console.log(">>>>>>>取消退出登录啦啦啦啦啦");
                });
        };

        // 处理菜单选择
        const handleMenuSelect = (index) => {
            state.activeMenu = index;
        };

        return {
            route,
            changeColor,
            clickLogout,
            isActive,
            handleMenuSelect,
            ...toRefs(state),
        };
    },
};
</script>

<style scoped>
.topBox {
    background: linear-gradient(135deg, #1e5799 0%, #207cca 51%, #2989d8 100%);
    /* background: linear-gradient(135deg, #1e5799 0%, #207cca 51%, #2989d8 100%); */
    /* height: 100%; */
    /* height: 60px; */
    padding: 0;
    position: relative;
    border-bottom: 1px solid #2a6aa5;
    height: 79px; /* 原高度基础上减小，可根据需要调整具体数值 */
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: space-between; /* 保持左右内容分布 */
}

.topBoxitem {
    width: 220px;
    height: 60px;
    padding: 0px;
    position: absolute;
    /* top: 0; */
    right: 0;
    color: #fff;
    font-size: 15px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
}

/* logo */
.logoImg {
    width: 260px;
    height: 109px;
    display: flex;
    justify-content: center;
    text-align: center;
    line-height: 109px;
    font-size: 28px;
    font-weight: bold;
    color: #ffffff;

    /* background-color: #1e5799; */
    /* box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); */
}

/* 导航栏子项样式 */
.navTitle {
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.mr {
    margin-right: 5px;
}

.w20 {
    width: 20px;
}

/* 左边框样式 */
.leftBox {
    background: #f8fafc;
    height: 93vh;
    width: 262px;
    box-sizing: border-box;
    border-right: 1px solid #e1e8ed;
}

.leftBoxConent {
    width: 260px;
    height: auto;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    flex-direction: column;
    text-align: center;
    padding: 5px;
    /* padding-top: 50px; */
    box-sizing: border-box;
}

.leftBoxConent :deep(.el-collapse) {
    background-color: #f8fafc !important;
    border: none !important;
    --el-collapse-content-bg-color: #f8fafc !important;
}


.leftBoxConent :deep(.el-collapse-item__wrap) {
    background-color: #f8fafc !important;
    border: none !important;
}

.leftBoxConent :deep(.el-collapse-item__header) {
    background-color: #f8fafc !important;
    border: none !important;
    padding-left: 12px !important;
    height: 50px !important;
    font-size: 16px !important;
    color: #333 !important;
    transition: all 0.3s ease !important;
}

.leftBoxConent :deep(.el-collapse-item__header):hover {
    background-color: #eef2f7 !important;
}

.leftBoxConent :deep(.el-collapse-item__content) {
    padding-bottom: 0 !important;
    background-color: #f8fafc !important;
}

.leftBoxConent :deep(.el-collapse-item__arrow) {
    color: #666 !important;
    font-size: 16px !important;
}

.leftBoxConent :deep(a) {
    display: block;
    transition: all 0.3s ease;
}

.leftBoxConent :deep(a:hover),
.leftBoxConent :deep(a:hover div) {
    background-color: #eef2f7 !important;
    border-radius: 4px;
}

.leftBoxConent :deep(.title_left) {
    padding: 8px 12px;
    margin: 4px 0;
    transition: all 0.3s ease;
}

.leftBoxConent :deep(.title_left:hover) {
    background-color: #eef2f7 !important;
    border-radius: 4px;
}

/* 内容样式 */
.conentBox {
    background: #f2f2f2;
    padding-top: 15px;
    padding-left: 15px;
    padding-right: 15px;
    box-sizing: border-box;
    height: 93vh;
}

/* 下拉选项样式 */
.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: #536d8e;
    display: flex;
    align-items: center;
}

/* 新的左边框样式 */
.title_left {
    text-align: left;
    margin: 12px 0;
    font-size: 16px;
    color: #9a9a9a;
    cursor: pointer;
    /* color: #cb4058; */
}

.line_bottom {
    width: 100%;
    height: 0;
    border-bottom: 1px solid #ebeef5;
}

.leftTitle {
    font-size: 16px;
    /* color: #9a9a9a; */
    letter-spacing: 0.05rem;
}

.mb {
    margin-bottom: 12px;
    color: #9a9a9a;
}

.mt {
    margin-top: 12px;
}

.leftBoxConent :deep(.el-collapse-item__content) {
    padding: 0 10px !important;
}

.leftBoxConent :deep(.el-collapse) {
    border: none !important;
}

.leftBoxConent :deep(.el-collapse-item) {
    margin-bottom: 8px;
}
</style>

<style>
/* 确认按钮颜色 */
.confirmBtn {
    background: #3a7bb8 !important;
    border: none !important;
    box-shadow: inset !important;
}

/* 图标样式 */
.fcc {
    display: flex;
    justify-content: center;
    align-items: center;
}

.fccIcon {
    width: 15px;
    height: 15px;
}

.iconMl {
    margin-left: 7px;
}
</style>

<style scoped>
/* 保持原有样式不变 */
/* 添加菜单相关样式 */
.leftBoxConent .el-menu {
    background-color: #f8fafc;
    border-right: none;
}

.leftBoxConent .el-menu-item,
.leftBoxConent .el-sub-menu__title {
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    color: #000;
    transition: all 0.3s ease;
}

.leftBoxConent .el-menu-item:hover,
.leftBoxConent .el-sub-menu__title:hover {
    background-color: #eef2f7 !important;
}

.leftBoxConent .el-menu-item.is-active {
    background-color: #eef2f7 !important;
    color: #3a7bb8;
}

.leftBoxConent .el-menu-item div,
.leftBoxConent .el-sub-menu__title div {
    display: flex;
    align-items: center;
}

/* 保持原有其他样式不变 */
.topBox {
    /* ... */
}

/* ... 其他样式保持不变 ... */
</style>